#include "articlecreator.h"
#include "article.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QUrl>
#include <QByteArray>
#include <QDebug>
#include <QEventLoop>

ArticleCreator::ArticleCreator(QObject *parent)
    : QObject{parent}, isSync(false)
{
    // 初始化 QNetworkAccessManager
    httpManager = new QNetworkAccessManager(this);
    connect(httpManager, &QNetworkAccessManager::finished, this, &ArticleCreator::onRequestFinished);
}

void ArticleCreator::setSyncMode(bool sync) {
    isSync = sync;
}

void ArticleCreator::createArticle(const QString &title, const QString &content, const QList<QString> &images) {
    // 设置 API URL
    QUrl url(article_backend + "/api/article");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 构建 JSON 数据
    QJsonObject json;
    json["title"] = title;
    json["content"] = content;

    QJsonArray imageArray;
    for (const QString& image : images) {
        imageArray.append(image);
    }
    json["images"] = imageArray;

    QJsonDocument doc(json);
    QByteArray data = doc.toJson();

    // 发送 POST 请求
    QNetworkReply* reply = httpManager->post(request, data);

    // 如果是同步请求，等待请求完成
    if (isSync) {
        QEventLoop loop;
        connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
        loop.exec();
    }
}

void ArticleCreator::onRequestFinished(QNetworkReply *reply) {
    // 处理响应
    if (reply->error() == QNetworkReply::NoError) {
        QByteArray response = reply->readAll();
        qDebug() << "Article created successfully:" << response;
        emit articleCreated(true, "Article created successfully");
    } else {
        qDebug() << "Failed to create article:" << reply->errorString();
        emit articleCreated(false, reply->errorString());
    }
    reply->deleteLater();
}
